<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 12-12-2
 * Time: 下午1:29
 * To change this template use File | Settings | File Templates.
 */
class Jwawa_Validate_Factory
{
    public static function validate($validators, $obj, $forTag = 'create'){
        if(!$obj){
            throw new Jwawa_BusinessException('VALIDATOR_ERROR_OBJECT_NOT_ALLOW_NULL');
        }

        foreach($validators as $fieldName => $validator){
            $forArray = (empty($validator['for']) ? array('create', 'update') : $validator['for']);
            $require =  (empty($validator['require']) ? false : true);
            $fieldValue = $obj->$fieldName;
            $rules = $validator['rules'];

//            if(in_array($forTag, $forArray)){
//                if(($fieldValue === null || (is_string($fieldValue) && $fieldValue === '')) && $require){
//                    throw new Jwawa_BusinessException('VALIDATOR_ERROR_REQUIRE', array($fieldName));
//                } else if($fieldValue !== null || (is_string($fieldValue) && $fieldValue !== '')){
//                    foreach ($rules as $ruleName => $ruleOpt) {
//                        $className = 'Jwawa_Validate_' . $ruleName;
//                        Zend_Loader::loadClass($className);
//                        $validatorInst = new $className($ruleOpt);
//                        if($ruleOpt && $ruleOpt['messages']){
//                            $validatorInst->setMessages($ruleOpt['messages']);
//                        }
//                        if(!$validatorInst->isValid($fieldValue)){
//                            $message = implode(',\n', $validatorInst->getMessages());
//                            throw new Jwawa_BusinessException('VALIDATE_ERROR', null,$message);
//                        }
//                    }
//                }
//            }

            if($require){
                if(in_array($forTag, $forArray) && empty($fieldValue)){
                    throw new Jwawa_BusinessException('VALIDATOR_ERROR_REQUIRE', array($fieldName));
                }
            }

            if(!empty($fieldValue)){
                foreach ($rules as $ruleName => $ruleOpt) {
                    $className = 'Jwawa_Validate_' . $ruleName;
                    Zend_Loader::loadClass($className);
                    $validatorInst = new $className($ruleOpt);
                    if($ruleOpt && $ruleOpt['messages']){
                        $validatorInst->setMessages($ruleOpt['messages']);
                    }
                    if(!$validatorInst->isValid($fieldValue)){
                        $message = implode(',\n', $validatorInst->getMessages());
                        throw new Jwawa_BusinessException('VALIDATE_ERROR', null,$message);
                    }
                }
            }
        }

        return true;
    }
}
